﻿using Microsoft.Extensions.Logging;
using S7.Net;
using S7.Net.Types;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PMS.SANY.MonOrderServer.Siemens
{
    public class SiemensReader
    {
        public ILogger<Worker> _logger;

        private Plc Client { set; get; }

        private Dictionary<string,bool> Values { set; get; }

        private Dictionary<string, DataItem> Items { set; get; }

        private SiemensReader()
        {
            Values = new Dictionary<string, bool>();
            Items = new Dictionary<string, DataItem>();
        }

        public SiemensReader(CpuType cpu, string ip, short rack = 0, short slot = 1)
        {
            Client = new Plc(cpu, ip, rack, slot);

            Values = new Dictionary<string, bool>();
            Items = new Dictionary<string, DataItem>();
            isReading = false;

            _ = StartAutoReadAsync();
        }

        public void Regist(string address)
        {
            try
            {
                if (!Items.ContainsKey(address))
                {
                    var item = DataItem.FromAddress(address);
                    item.Count = 1;
                    item.VarType = VarType.Bit;
                    Items.Add(address, item);
                }
                if (!Values.ContainsKey(address))
                {
                    Values.Add(address, false);
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        public bool Read(string address)
        {
            return Values[address];
        }

        private bool isReading=false;
        public async Task StartAutoReadAsync()
        {
            if (isReading) return;
            else isReading = true;

            while(isReading)
            {
                try
                {                    
                    foreach(var item in Items)
                    {
                        try
                        {
                            if (!Client.IsConnected) Client.Open();

                            //var di = item.Value;
                            var di = DataItem.FromAddress(item.Key);
                            //var value = Convert.ToBoolean(Client.Read(di.DataType, di.DB, di.StartByteAdr, di.VarType, di.Count, di.BitAdr));
                            var value2 = Convert.ToBoolean(Client.Read(item.Key));
                            if (Values.ContainsKey(item.Key)) Values[item.Key] = value2;
                            else Values.Add(item.Key, value2);

                            //string address = "DB6000.DBX128.0";
                            //if (item.Key == address)
                            //{
                            //    string msg2 = string.Format("===>{0}=>{1}.{2}={3}"
                            //        , System.DateTime.Now.ToString("mm:ss.fff")
                            //        , Client.IP
                            //        , address
                            //        , value2);
                            //    _logger.LogInformation(msg2);
                            //}
                        }
                        catch(Exception ex)
                        {
                            _logger.LogError("SiemensReader.Read [" + Client.IP + "==>" + item.Key + "] Error:" + ex.Message);
                        }
                    }
                    
                    
                }
                catch (Exception ex)
                {
                    _logger.LogError("SiemensReader.Read" + ex.Message);
                }
                await Task.Delay(1000);
            }

            isReading = false;
        }
    }
}
